// pages/info/info.js
import { DBPost } from '../../db/DBPost.js';
var util = require('../../utils/util.js');  

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bookid:null,
    booktitle:null,
    bookauthor:null,
    bookcountry:null,
    bookpublisher:null,
    bookdetail:null,
    bookdate:null,
    bookisbn:null,
    hosterid:null,
    hostername:null,
    bookimage:null,
    bookowner: null,
    bookownerid: null,
    bookrentrecord: null,
    bookrentdate: null,
    bookrenew: null,

    accesstoken:null,
    formid:null,
    appid: getApp().globalData.appID,

    takenhour: null,
    allowhour: null,
    rentlimit: null,
    
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    //收藏功能，实例化DBPost,传入参数postid
    this.dbPost = new DBPost(options.bookid)
    this.postData = this.dbPost.getPostItemById().data
    console.log(this.postData)
    this.setData({
      post: this.postData
    })

    var that = this

    console.log(options)
    this.setData(
      {
        bookid: options.bookid,
        hosterid:options.hosterid
      }
    )
    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Hoster').where
      ({
        _openid: _.eq(this.data.hosterid)
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              hostername: res.data[0].names,
            }
          )
          console.log('用户名查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

    //借阅设置
    db.collection('RentPara')
      .where
      ({
        rtype: _.eq('图书')
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              rentlimit: res.data[0].rentDay,
            }
          )
          console.log('管理员查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  

    // var timestamp = new Date().getHours()
    // console.log('当前时间', timestamp)
    // this.setData
    //   ({
    //     takenhour: timestamp
    //   })

    // setInterval(function () {
    // wx.request({ 
    //   // 获取token
    //       url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
    //       data: {
    //         appid: getApp().globalData.appID,
    //         secret: getApp().globalData.appSecret
    //       },
    //       success: function (res) 
    //       {
    //         console.log(res.data.access_token)
    //         that.setData(
    //           {
    //             accesstoken: res.data.access_token,
    //           }
    //         )
    //       }
    //     })
      //循环执行代码
    // },10000) //循环时间 这里是1秒

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


    var timestamp = new Date().getHours()
    console.log('当前时间', timestamp)
    this.setData
      ({
        takenhour: timestamp
      })
      
    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Books').where
      ({
        _id: _.eq(this.data.bookid)
      })
      .get
      ({
        success: res => {
  
          this.setData(
            {
              booktitle: res.data[0].title,
              bookauthor: res.data[0].author,
              bookpublisher: res.data[0].publisher,
              bookowner: res.data[0].owner,
              bookdata: util.formatTime(res.data[0].pubdate),
              bookdetail: res.data[0].summary,
              bookimage: res.data[0].image,
              collectionStatus: res.data[0].collectionStatus,
              collectionNum:res.data[0].collectionNum,
              bookownerid: res.data[0].ownerid,
              bookrentrecord: res.data[0].rentrecord,
              bookrentdate: res.data[0].rentdate,
              bookrenew: res.data[0].renew,
            }
          )
          console.log('数据库查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })



  },

  //点击收藏按钮对应的方法
  onCollectionTap: function (event) { 
    var newData = this.dbPost.collect()   //调用DBPost的collect方法
    // console.log(newData)
    //重新绑定数据
    this.setData({
      'post.collectionStatus': newData.collectionStatus,
      'post.collectionNum': newData.collectionNum
    })

    wx.showToast({
      title: newData.collectionStatus ? "收藏成功" : "取消收藏",
      duration: 1000,
      icon: "success",
      mask: true
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //借阅按钮
  rentbook: function () {

    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);

    this.setData
      ({
        takenhour: timestamp
      })


    if (this.data.hostername != '无') {
      var aflag = 0
      var bookownertem = this.data.bookowner
      var bookowneridtem = this.data.bookownerid
      var length = bookownertem.length
      var bookrentrecordtem = this.data.bookrentrecord
      var bookrentdatetem = this.data.bookrentdate

      for (var i = 0; i < length; i++) {
        if (bookowneridtem[i] == this.data.hosterid) {
          wx.showToast({
            title: '您已经借阅此书',
            icon: 'error',
            duration: 2000          //提示的延迟时间
          })
          aflag = 1
          break
        }
      }

      for (var j = 0; j < length; j++) {
        if (bookowneridtem[j] == '空' && aflag == 0) {
          bookrentrecordtem = bookrentrecordtem + 1
          bookowneridtem[j] = this.data.hosterid
          bookownertem[j] = this.data.hostername
          bookrentdatetem[j] = this.data.takenhour
          this.setData
            ({
              bookrentdate: bookrentdatetem,
              bookowner: bookownertem,
              bookownerid: bookowneridtem,
              bookrentrecord: bookrentrecordtem
            })
          wx.cloud.callFunction
            ({
              // 云函数名称
              name: 'rent',
              // 传给云函数的参数
              data:
              {
                bookid: this.data.bookid,
                bookowner: this.data.bookowner,
                bookownerid: this.data.bookownerid,
                hostername: this.data.hostername,
                hosterid: this.data.hosterid,
                bookrentrecord: this.data.bookrentrecord,
                bookrentdate: this.data.bookrentdate,
              },

              success: function (res) {
                console.log(res)
              },

              fail: console.error
            })

          wx.showToast({
            title: '借书成功',
            icon: 'error',
            duration: 2000          //提示的延迟时间
          })
          break

        }
      }



    } else {
      wx.showToast({
        title: '你必须先实名注册',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })
    }

  },

  formSubmit: function (e) {
    
    console.log('form发生了submit事件，fromId为：', e.detail.formId)
    this.setData
    ({
      formid:e.detail.formId
    })
  },
  
  //还书按钮
  returnbook: function () {
    var bookownertem = this.data.bookowner
    if (this.data.hostername != '无') {
      var bookownertem = this.data.bookowner
      var bookowneridtem = this.data.bookownerid
      var bookrenewtem = this.data.bookrenew
      var length = bookownertem.length

      for (var i = 0; i < length; i++) {
        if (bookowneridtem[i] == this.data.hosterid) {
          bookowneridtem[i] = '空'
          bookownertem[i] = '无人'
          bookrenewtem[i] = false
          this.setData
            ({
              bookowner: bookownertem,
              bookownerid: bookowneridtem
            })
        }
        wx.cloud.callFunction({
          // 云函数名称
          name: 'return',
          // 传给云函数的参数
          data: {
            bookid: this.data.bookid,
            bookownerid: this.data.bookownerid,
            bookowner: this.data.bookowner
          },
          success: function (res) {
            console.log(res)
          },
          fail: console.error
        })


        wx.showToast({
          title: '还书成功！',
          icon: 'error',
          duration: 2000          //提示的延迟时间
        })

      }

    } else {
      wx.showToast({
        title: '你必须先实名注册',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })
    }
  }
})

